package com.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wms.dao.WReturnStoreDao;
import com.wms.dao.WStockDao;
import com.wms.entity.WEntryStore;
import com.wms.entity.WOutStore;
import com.wms.entity.WReturnStore;
import com.wms.entity.WStock;
import com.wms.mytool.Result;
import com.wms.service.CommonService;
import com.wms.service.WReturnStoreService;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 退货表(WReturnStore)表服务实现类
 *
 * @author Li Xiaoyu
 * @since 2023-11-26 19:50:01
 */
@Service("wReturnStoreService")
public class WReturnStoreServiceImpl implements WReturnStoreService {
    @Resource
    private WReturnStoreDao wReturnStoreDao;
    @Resource
    private WStockDao wStockDao;
    @Resource
    private CommonService commonService;

    @Override
    public Result selectAll() {
        return new Result(200, this.wReturnStoreDao.selectAll(), "success");
    }

    @Override
    public Result addReturnStore(List<WReturnStore> wReturnStore) {
        //查询所有退货单号
        int[] arr = this.wReturnStoreDao.selectAllBackId();
        int max = 0;
        //退货单号存在
        if (arr.length>0) {
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] > max) {
                    max = arr[i];
                }
            }
        } else {
            //退货单号不存在，从10000开始
            max = 300000;
        }
        Date date = new Date();
        for (WReturnStore returnStore : wReturnStore) {
            Result result=this.commonService.updateStock(returnStore.getSid(), returnStore.getPid(), returnStore.getPNum(), true);
            if(result.getCode()==200){
                //退货单号递增
                returnStore.setBackId(max + 1);
                returnStore.setCreateTime(date);
                //新增退货信息
                this.wReturnStoreDao.insert(returnStore);
                //查询仓库库存
                WStock wStock = this.wStockDao.selectByPidSid(returnStore.getPid(), returnStore.getSid());
                //有库存，库存量增加
                wStock.setNum(wStock.getNum() + returnStore.getPNum());
                wStock.setMender(returnStore.getCreator());
                wStock.setUpdateTime(date);
                this.wStockDao.updateById(wStock);
            }else{
                return result;
            }
        }
        return new Result(200, "", "退货成功");
    }

    @Override
    public Result deleteReturnStore(Integer id) {
        QueryWrapper<WReturnStore> qw = Wrappers.query();
        qw.eq("id", id);
        int i = this.wReturnStoreDao.delete(qw);
        if (i == 1) {
            return new Result(200, i, "删除成功");
        } else {
            return new Result(400, null, "删除失败");
        }
    }
}
